<template>
	<view class="content">
		<view>
			<view class="header">
				<view class="back-button" @click="goBack">
					<uni-icons type="left" size="20" color="#000"></uni-icons>
				</view>
				<view class="title">编辑{{ editTitle }}</view>
			</view>

			<view class="input-container">
				<uni-easyinput v-model="inputValue" :placeholder="'请输入' + editTitle" :clearable="true"
					class="easyinput"></uni-easyinput>
				<button class="save-btn" @click="saveUserInfo">保存</button> <!-- 保存按钮 -->
			</view>
		</view>
	</view>
</template>

<script>
	import {
		editUserInfo
	} from '@/api/user.js'; // 引入更新用户信息的接口
	export default {
		data() {
			return {
				field: '',
				editTitle: '姓名', // 存储传入的编辑项
				inputValue: '' // 输入框的内容
			}
		},
		onLoad(options) {
			this.editTitle = options.field === 'name' ? '姓名' : '简介';
			this.inputValue = options.value === 'null' ? '' : options.value || '';
			this.field = options.field;
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			// 保存用户信息
			async saveUserInfo() {
				if (this.inputValue != '') {
					const userInfo = {
						[this.field]: this.inputValue
					};
					try {
						console.log(userInfo)
						const response = await editUserInfo(userInfo);
						if (response.code === 200) {
							uni.$emit('updateUserInfo', userInfo);
							this.goBack();
						} else {
							uni.showToast({
								title: '更新失败，请重试',
								icon: 'none'
							});
						}
					} catch (error) {
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					}
				} else {
					uni.showToast({
						title: this.editTitle + '不能为空',
						icon: 'none'
					});
				}
			}
		}
	}
</script>

<style>
	.content {
		width: 750rpx;
		min-height: 100vh;
		background-color: white;
		position: relative;
	}

	.header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding-top: 100rpx;
		padding-bottom: 30rpx;
		padding-left: 32rpx;
		padding-right: 32rpx;
		background-color: #f8f8f8;
		border-bottom: 1rpx solid #ddd;
	}

	.back-button {
		width: 64rpx;
		height: 64rpx;
		padding-top: 10rpx;
		align-items: center;
		/* 让图标在 back-button 内居中 */
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.title {
		font-size: 32rpx;
		font-weight: 400;
		text-align: center;
		/* 使标题居中 */
		flex: 1;
		/* 占据剩余空间，确保标题居中 */
	}

	.input-container {
		padding: 24rpx;
		display: flex;
		flex-direction: row;
		/* 水平方向排列输入框和保存按钮 */
		align-items: center;
		/* 垂直居中 */
		gap: 16rpx;
		/* 输入框和按钮之间的间隙 */
	}

	.easyinput {
		width: 100%;
		font-size: 32rpx;
		padding: 16rpx;
		border: 1rpx solid #ddd;
		border-radius: 8rpx;
	}

	.save-btn {
		background-color: #007aff;
		/* 蓝色背景 */
		color: white;
		/* 白色字体 */
		font-size: 28rpx;

		border-radius: 8rpx;
		border: none;
		cursor: pointer;
	}

	.save-btn:hover {
		background-color: #005bb5;
		/* 按钮悬停时的颜色 */
	}
</style>